package com.android.enjoymax;

import java.util.ArrayList;
import java.util.List;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class Map extends MapActivity implements OnClickListener{
	
	public static final String TAG = "Loc";
	public static final int ZOOM_LEVEL = 18;
	public static final String CURRENT_LOCATION = "Current Location";
	public static final long MIN_TIME = Integer.MAX_VALUE;
	public static final float MIN_DISTANCE = 100;
	    
	private LocationManager lm;
	private MyLocationListener locationListener;
	
	private MyItemizedOverlay itemizedOverlay;
	private MyItemizedOverlay itemizedOverlayForCurrentLoc;
	private List<Overlay> mapOverlays; 
	private MapController mapController;
	
	private GeoPoint pointPresent;
	private static ListView listView;
	
	double latitude = 37.78802;
	double longitude = -122.399797;
	
	
 @Override
 public void onCreate(Bundle savedInstanceState) {
	  super.onCreate(savedInstanceState);
      setContentView(R.layout.map);
      
      lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
      locationListener = new MyLocationListener();
      
      lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, locationListener);
      lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DISTANCE, locationListener);
      
      listView = (ListView) findViewById(R.id.mylist);
      
      
      String[] listItems = new String[] {"List Item1","List Item 2","List Item3","List Item1","List Item 2","List Item3","List Item1","List Item 2","List Item3"};
      ArrayAdapter<String> tempAdapter = new ArrayAdapter<String>(getApplicationContext(),
              android.R.layout.simple_list_item_1, android.R.id.text1,listItems);

      listView.setAdapter(tempAdapter);  
      
      
//      lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, locationListener);
  //    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DISTANCE, locationListener);
      
      // Set Map Parameters.
      MapView mapView = (MapView) findViewById(R.id.mapview);
  	  mapView.setStreetView(true);
  	  mapView.setTraffic(true);
  	  mapView.setBuiltInZoomControls(true);
  	
   	  mapOverlays = mapView.getOverlays();
	  Drawable drawable = this.getResources().getDrawable(R.drawable.pushpin);
	  Drawable forCurrent = this.getResources().getDrawable(R.drawable.mylocation);
		
	  //itemizedOverlay = new MyItemizedOverlay(drawable);
	  itemizedOverlay = new MyItemizedOverlay(drawable, this);
	  itemizedOverlayForCurrentLoc = new MyItemizedOverlay(forCurrent, this);
	  
	  new MakeItinerary().makeItinerary(getApplicationContext(), itemizedOverlay, mapOverlays, 3, longitude, latitude, 500, 4);
	  
	  mapController = mapView.getController();
  	  mapController.setZoom(ZOOM_LEVEL);
  	  plotPoints();
  	  
  	  
 	 

   
}
 
 
     
     private void plotPoints() {
    	 
     }
     
	 @Override
		public void onClick(View v) {
	        
		
		}
	 
	  public void addOverlay(GeoPoint pinCoordinates, String title, String snippet) {
	    	OverlayItem overlayItem = new OverlayItem(pinCoordinates, title, snippet);
	    	
	    	if(title.equals(CURRENT_LOCATION)) {
	    		itemizedOverlayForCurrentLoc.addOverlay(overlayItem);
	    		mapOverlays.add(itemizedOverlayForCurrentLoc);
	    	}
	    	else {
	            itemizedOverlay.addOverlay(overlayItem);
	            mapOverlays.add(itemizedOverlay);
	    	}
	    }
	  
	  private GeoPoint coordinatesToGeoPoint(Location location) {
	    	final int multiplier = (int) Math.pow(10, 6);
	    	final int tempLatitude = (int)(location.getLatitude() * multiplier);
	    	final int tempLongitude = (int) (location.getLongitude() * multiplier);
	    	
	    	System.out.println(tempLatitude + " "+ tempLongitude);
	    	return new GeoPoint(tempLatitude, tempLongitude);
	    }
	  
	  public static GeoPoint coordinatesToGeoPoint(double latitudeLoc, double longitudeLoc) {
	    	final int multiplier = (int) Math.pow(10, 6);
	    	final int tempLatitude = (int)(latitudeLoc * multiplier);
	    	final int tempLongitude = (int) (longitudeLoc * multiplier);
	    	
	    	//System.out.println(tempLatitude + " "+ tempLongitude);
	    	return new GeoPoint(tempLatitude, tempLongitude);
	    }
	  
	  class MyLocationListener implements LocationListener 
	    {
			@Override
			public void onLocationChanged(Location location) {
				longitude = location.getLongitude();
		        latitude = location.getLatitude();
		        
		         Log.d(TAG, "my lat is " + latitude + " and lon is " + longitude);
		         
		         itemizedOverlayForCurrentLoc.resetMap();
		         
		         pointPresent = coordinatesToGeoPoint(location);
		         //Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
		         mapController.animateTo(pointPresent);
		         mapController.setCenter(pointPresent);
		         addOverlay(pointPresent, CURRENT_LOCATION, "");
			}

			@Override
			public void onProviderDisabled(String provider) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onProviderEnabled(String provider) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onStatusChanged(String provider, int status, Bundle extras) {
				
				//new RequestTask().execute(new String[] {URL + "GetStopsByLatLon", "GetStopsByLatLon"});
			}
	        	
	    }

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	
	

	class MyItemizedOverlay extends ItemizedOverlay {
	   
		private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>(); 
		private Context mContext; 
		
		public MyItemizedOverlay(Drawable defaultMarker, Context context) {
			super(boundCenterBottom(defaultMarker));
			mContext = context; 
			populate(); 
			// TODO Auto-generated constructor stub
		}
		
		public MyItemizedOverlay(Drawable defaultMarker) {
			super(boundCenterBottom(defaultMarker));
			//mContext = MyApplication.get();
			
			//populate(); 
			// TODO Auto-generated constructor stub
		}
		
		@Override
		protected boolean onTap(int index) {
			
			OverlayItem item = mOverlays.get(index);
		
			  AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
			  
			  if (item == null || item.getTitle().equals("blob")) {
				  return true;  
			  }
			  
			  dialog.setTitle(item.getTitle());
			  
			  // Since we don't need to show snippet for the Current Location.
			/**
			  if (!item.getTitle().equals(MTDAppActivity.CURRENT_LOCATION)) {
			      dialog.setMessage(item.getSnippet());
			  }
			  **/
			 // dialog.show();
			  
			  startActivity(new Intent(Map.this, Pictures.class));
			  
			  // Check to see that its not our current location.
			  /**
			  if (!item.getTitle().equals(MTDAppActivity.CURRENT_LOCATION)) {
				  Log.d(MTDAppActivity.TAG, "title is " + item.getTitle() + " and snippet is " + item.getSnippet());
				  Log.d(MTDAppActivity.TAG, "where as my expected is " + MTDAppActivity.globalStopIds.get(index));
				  
			      MTDAppActivity.get().new GetDeparturesByStopHandler().execute(MTDAppActivity.URL + "GetDeparturesByStop", MTDAppActivity.globalStopIds.get(index));
			  }
			  
			  **/
			
			return true;
		}
		
		public void addOverlay(OverlayItem overlay) {
			mOverlays.add(overlay);
			populate();
		}
	    
		public ArrayList<OverlayItem> getMyOverlayItems() {
		    return mOverlays;	
		}
		
		public void resetMap() {
			mOverlays.clear();
			populate();
		}
		
		@Override
		protected OverlayItem createItem(int arg0) {
			// TODO Auto-generated method stub
			return mOverlays.get(arg0);
		}
		
		@Override
		public int size() {
			return mOverlays.size();
		}


	}


	    
}
